<?php

namespace app\controller;

use app\BaseController;
use app\message;
use app\model\ClueCommunicateRecord;
use app\model\ClueMobile;
use app\model\CluePerson;
use app\model\CluePersonAllocationRecord;
use app\model\CluePersonCertificate;
use app\model\OrderEnterpriseCompany;
use app\model\OrderEnterpriseExchange;
use app\model\OrderLog;
use app\model\OrderOtherCertificateBusiness;
use app\model\SystemCertificate;
use app\model\SystemOperateLog;
use app\model\User;
use app\model\WorkPlan;
use app\Request;
use app\service\Certificate;
use app\service\CluePersonServer;
use app\service\CustomField;
use app\service\Power;
use app\service\redis;
use app\service\RedisService;
use app\service\System;
use app\service\SystemMenuDataPower;
use app\stateData;
use app\validate\Clue;
use app\validate\ClueEnterprise as ClueEnterpriseValidate;
use app\validate\ClueUPersonList;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;

class CluePersonAbility extends BaseController
{

    /**
     * 线索库 人才控制器
     */

    //个人人才库列表
    public function uPersonList(
        Request           $request,
        Power             $power,
        CluePerson        $person,
        \app\service\Clue $clue,
        Certificate       $certificate,
        SystemCertificate $certificateModel,
        CluePersonServer  $cluePersonServer,
        CustomField $customField,
        RedisService $redisService
    ){
        $aliasId = $request->get('aliasId');

        $page = $request->get('page') ?: 1;
        $pageNum = $request->get('pageNum') ?: stateData::$_page;

        $param = $request->get();

        $uid = $request->param('user_login_id');
        //参数验证
        $validate = new ClueUPersonList();
        if (!$validate->check($param)) {
            return ReJson(message::$ERROR_CODE, $validate->getError(), []);
        }
        //判断参数是否有值
        $flag = false;
        $key_arr = [
            'aliasId',
            'page',
            'pageNum',
            'user_login_id',
        ];
        foreach ($param as $key => $item) {
            if (in_array($key, $key_arr)) {
                continue;
            }
            if ($item) {
                $flag = true;
                break;
            }
        }
        //将每个参数整合为条件
        $person_ids = $cluePersonServer->spliceWhere($param);
        $person_ids = !$person_ids ? [0] : $person_ids;
        //拼接where条件
        $where = [];
        if (empty($aliasId)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);
        //字段权限
        $fieldListTree = $power->getUserFieldPower($aliasId, $uid);

        //用户person_ID
        $uid_person_ids = $person->getUidDataPersonId($uid);

        $person_ids = handlePersonIds($uid_person_ids, $person_ids, $flag);
        //处理用户可看到的人才ID
        $user_login_id = $uid;
        $dataId = $person->getUidData($user_login_id, $person_ids, $pageNum, $page);

        $result = $redisService->getPersonDataReSet ($dataId,$uid);

        foreach($result as $key => $value){
            $result[$key] = $customField->listCustomFieldHandle($value);
        }
        $pages['total'] = $person->getUidDataCount($uid, $person_ids);

        $pages['pageNumber'] = $pageNum;
        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, [
            'data' => $result,
            'power' => $fieldListTree
        ], $pages);
    }


    public function handlePersonIds($uid_person_ids, $person_ids, $flag)
    {
        //chern添加数组重新索引
        $person_ids = array_values($person_ids);
        if ($uid_person_ids && !$person_ids) {
            $person_ids = $uid_person_ids;
        } elseif (!$uid_person_ids && $person_ids) {
            $person_ids = $uid_person_ids;
        } elseif ($uid_person_ids && $person_ids) {
            if (count($person_ids) == 1 && $person_ids[0] == 0 && !$flag) {
                $person_ids = $uid_person_ids;
            } else {
                $person_ids = array_intersect($person_ids, $uid_person_ids);
            }

        }
        return $person_ids;
    }


    //管理人才库列表
    public function personList(
        Request            $request,
        Power              $power,
        CluePerson         $person,
        \app\service\Clue  $clue,
        CluePersonServer   $cluePersonServer,
        System             $system,
        \app\service\Order $order,
        SystemMenuDataPower $dataPower,
        RedisService $redisService
    ){

        $aliasId = $request->get('aliasId');

        $page = $request->get('page') ?: 1;

        $pageNum = $request->get('pageNum') ?: stateData::$_page;

        $uid = $request->get('user_login_id');

        $param = $request->get();
        //参数验证
        $validate = new ClueUPersonList();
        if (!$validate->check($param)) {
            return ReJson(message::$ERROR_CODE, $validate->getError(), []);
        }

        //判断参数是否有值
        $flag = false;
        $key_arr = [
            'aliasId',
            'page',
            'pageNum',
            'user_login_id',
        ];
        foreach ($param as $key => $item) {
            if (in_array($key, $key_arr)) {
                continue;
            }
            if ($item) {
                $flag = true;
                break;
            }
        }

        if (empty($aliasId)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $fieldListTree = $power->getUserFieldPower($aliasId, $uid);

        //将每个参数整合为条件
        $person_ids = $cluePersonServer->spliceWhere($param);

        //根据条件查询用户范围
        $userData = $power->getUserDataRange($uid);

        $data = $dataPower->getOpenSeaPower($uid);

        //用户person_ID
        $uid_person_ids = $person->newGetRangeDataPersonId($userData,$data,$param);
        $person_ids = $this->handlePersonIds($uid_person_ids, $person_ids, $flag);
        //根据用户范围查询人才数据
        $listId = $person->newGetRangeData($userData, $pageNum, $person_ids, $page);

//        $result = $clue->personData($list, $uid);
        //查询缓存是否与数据库ID一致，不一致同步到redis
        $result = $redisService->getPersonDataReSet(page($listId,$page,$pageNum,'','',false),$uid);

        $pages['total'] = $person->newGetRangeDataCount($userData, $person_ids);
//        $pages['total'] = count($result);
        $pages['pageNumber'] = $pageNum;

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, [
            'result' => $result,
            'power' => $fieldListTree
        ], $pages);
    }

    //添加人才
    public function addPerson(
        Request                    $request,
        CluePerson                 $clueModel,
        OrderLog                   $orderLog,
        ClueMobile                 $mobileModel,
        ClueCommunicateRecord      $commRecord,
        CluePersonCertificate      $cretificate,
        CluePersonAllocationRecord $allRecord,
        Certificate                $certificateSer,
        WorkPlan                   $workPlanModel,
        \app\model\UserMessage     $userMessageModel,
        CustomField                $customField,
        SystemOperateLog $systemOperateLogModel
    ){
        /**
         * @param $f_uid
         * @param $person_name
         * @param $person_id_card
         *    //选填
         * @param $certificate_id //证书专业id 可以查找相关父类证书信息
         * @param $project
         * @param $certificate_period_of_validity
         * @param $certificate_b
         * @param $certificate_b_period_of_validity
         * @param $social_security
         * @param $certificate_log_off
         *
         * //联系电话
         * @type array $mobArr
         * @param $mobile
         * @param $status
         *
         * //其他证书
         * @type array $certificate
         * @param $certificate_type
         * @param $certificate_speciality
         * @param $certificate_period_of_validity
         * @param $register
         *
         * //沟通记录
         * @type array $communicate
         * @param $intention
         * @param $call
         * @param $communicate_content
         * @param $communicate_date
         * @param $communicate_uid
         */
        //拆分证书
        $param = $certificateSer->splitCer($request->post());

        $param['f_uid'] = $uid = $request->param('user_login_id');
        $param['is_f'] = 2;//新建默认分配人是自己

//        $param['allocation_date'] = date('Y-m-d H:i:s');//新建默认分配人是自己

        Db::startTrans();
        //自定义字段格式化
        $param['custom'] = json_encode($param['custom'], JSON_UNESCAPED_UNICODE);

        //处理自定义字段
        $param['custom'] = $customField->addAndEditCustomFieldHandle($param['custom']);
        try {
            Validate(Clue::class)->scene('personIdCard')->check($param);

            //查询身份证是否已经存在
            if ($clueModel->getPersonIdCard($param['person_id_card']) && !empty($param['person_id_card'])) {
                return ReJson(message::$ERROR_CODE, message::$ERR_PERSON_ID_CARD_ISSET);
            }
            //添加人才记录
            $p_id = $clueModel->addPersonModel($param)->id;

            //联系电话
            if (isset($param['mobarr']) & !empty($param['mobarr'])) {
                $mobArr = $param['mobarr'];
                foreach ($mobArr as $key => &$iValue) {
                    if (!$iValue['mobile']) {
                        unset($mobArr[$key]);
                        continue;
                    }
                    Validate(Clue::class)->scene('mobile')->check($iValue);
                    $iValue['clue_p_id'] = $p_id;
                }
                if ($mobArr) {
                    $mobileModel->addAllPersonMobileModel($mobArr);
                }
            }

            //其他证书
            if (isset($param['otherCertificate']) & !empty($param['otherCertificate'])) {
                $certificate = $param['otherCertificate'];
                $data = [];
                foreach ($certificate as $key => &$jValue) {
                    if (!$jValue['certificate_id']) {
                        unset($certificate[$key]);
                        continue;
                    }
//                    Validate(Clue::class)->scene ('otherCertificate')->check($jValue);
                    //拆分证书

                    $certificates = $certificateSer->splitCer($jValue);

                    //如果certificate为一维数组转字符串入库
                    if (is_array($certificates['certificate_id'])) {
                        $certificates['certificate_id'] = implode(',', $certificates['certificate_id']);
                    }
                    $certificates['clue_p_id'] = $p_id;

                    $data[] = $certificates;
                }

                if ($data) {
                    $cretificate->addAllPersonCertificateModel($data);
                }
            }

            //沟通记录
            if (isset($param['communicate']) & !empty($param['communicate'])) {
                $communicate = $param['communicate'];
                foreach ($communicate as $key => &$kValue) {
                    if (!$kValue['communicate_date']) {
                        unset($certificate[$key]);
                        continue;
                    }


                    $kValue['communicate_uid'] = $request->param('user_login_id');
//                    Validate(Clue::class)->scene('communicate')->check($kValue);
                    $kValue['clue_p_id'] = $p_id;

                    if (!empty($kValue['communicate_content']) || !empty($kValue['call']) || !empty($kValue['intention']) || !empty($kValue['next_communicate_date'])){
                        //添加沟通记录
                        $commRData = $commRecord->addPersonCommunicateRecordModel($kValue);

                        //添加计划任务
                        $wData = $workPlanModel->addPlanModel([
                            'custom_name' => $param['person_name'],
                            'plan_date' => $kValue['next_communicate_date'],
                            'plan_content' => $kValue['next_plan_content'],
                            'create_uid' => $param['f_uid'],
                            'type' => 1
                        ]);

                        //如果没有沟通记录 那么沟通记录ID为0
                        if (isset($commRData)){
                            //添加信息提醒
                            $userMessageModel->addPlanModel($param['person_name'], $param['f_uid'], $uid,$commRData->id, $kValue['next_communicate_date']);
                        }else{
                            //添加信息提醒
                            $userMessageModel->addPlanModel($param['person_name'], $param['f_uid'], $uid,0, $kValue['next_communicate_date']);
                        }
                    }
                }
            }

            //添加人才生命周期
            $allRecord->addPersonAllocationModel($p_id, message::$SUCC_PERSON_ADD, $request->param('user_login_id'));

            //添加操作日志
//            $orderLog->addDataModel([
//                'submit_id'=>$request->get ('user_login_id'),
//                'message'=>message::$ORDER_PERSON_ADD,
//                'type'=>1
//            ]);
            $systemOperateLogModel->addOperate ($uid,message::$RERSON,message::$SUCC_PERSON_ADD);

            Db::commit();
        } catch (ValidateException|\Exception $e) {
            Db::rollback();
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }

        return ReJson(message::$SUCC_CODE, message::$SUCC_INSERT_DATA);
    }

    //修改人才基本信息
    public function editPersonBasicInfo(
        Request                    $request,
        CluePerson                 $clueModel,
        CluePersonAllocationRecord $allRecord,
        SystemOperateLog           $log,
        \app\service\Certificate   $certificateSer,
        CustomField $customField,
        RedisService $redisService,
        SystemOperateLog $systemOperateLogModel
    ){
        $param = $certificateSer->splitCer($request->post());
        $uid = $request->post ('user_login_id');

        try {
            if (!isset($param['id'])) throw new \think\Exception(message::$ERR_PARAM_EMPTY, message::$ERROR_CODE);

            Validate(Clue::class)->check($param);
            unset($param['f_uid']);
            if(isset($param['custom'])){
                //处理自定义字段
                $param['custom'] = $customField->addAndEditCustomFieldHandle($param['custom']);
            }

            $clueModel->editPersonModel($param);
            //同步修改缓存内容
            $data = $clueModel->getIdPersonInfo ($param['id']);
            $redisService->updatePersonData($data,$uid);

        } catch (ValidateException|\Exception $e) {
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }

        //添加人才生命周期
//        $allRecord->addPersonAllocationModel ($param['id'],message::$SUCC_PERSON_UPDATE_BASIC);
        $systemOperateLogModel->addOperate ($uid,message::$RERSON,message::$SUCC_PERSON_UPDATE_BASIC);

        return ReJson(message::$SUCC_CODE, message::$SUCC_UPDATE);
    }

    /**
     *联系电话
     */

    //修改联系电话
    public function editPersonMobile(
        Request                    $request,
        ClueMobile                 $mob,
        SystemOperateLog $systemOperateLogModel
    ){
        $param = $request->post();
        $uid = $request->post ('user_login_id');

        try {
            if (!isset($param['id'])) throw new \think\Exception(message::$ERR_PARAM_EMPTY, message::$ERROR_CODE);

            Validate(Clue::class)->scene('mobile')->check($param);

            $mob->editMobileModel($param);
        } catch (ValidateException|\Exception $e) {
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }

        //添加人才生命周期
//        $allRecord->addPersonAllocationModel ($param['clue_p_id'],message::$SUCC_PERSON_UPDATE_MOBILE);
        $systemOperateLogModel->addOperate ($uid,message::$RERSON,message::$SUCC_PERSON_UPDATE_MOBILE);

        return ReJson(message::$SUCC_CODE, message::$SUCC_UPDATE);
    }

    //删除联系电话
    public function delMobile(
        Request                    $request,
        ClueMobile                 $mob,
        SystemOperateLog $systemOperateLogModel
    ){
        $param = $request->post();
        $uid = $request->post ('user_login_id');

        if (!isset($param['id'])) throw new \think\Exception(message::$ERR_PARAM_EMPTY, message::$ERROR_CODE);

        if ($mob->delMobileModel($param['id'])) {
            //添加人才生命周期
//            $allRecord->addPersonAllocationModel ($param['clue_p_id'],message::$SUCC_PERSON_DELETE_MOBILE);
            $systemOperateLogModel->addOperate ($uid,message::$RERSON,message::$SUCC_PERSON_DELETE_MOBILE);

            return ReJson(message::$SUCC_CODE, message::$SUCC_DATELE_DATA);
        }

        return ReJson(message::$ERROR_CODE, message::$ERR_DATELE_DATA);
    }

    //添加联系电话
    public function addMobile(
        Request $request,
        ClueMobile $mob,
        SystemOperateLog $systemOperateLogModel
    ){
        $paramArr = $request->post('arr');
        $uid = $request->post ('user_login_id');

        try {
            foreach ($paramArr as $value) {
                Validate(Clue::class)->scene('mobile')->check($value);

                //查询当前条id是否已经存在数据库
                if (isset($value['id'])) {
                    $find = $mob->getIdFindDataModel($value['id']);

                    if (!empty($find)) {
                        //存在更新
                        $mob->editMobileModel($value);
                    } else {
                        $mob->addProsonMobileModel($value);
                    }
                } else {
                    $mob->addProsonMobileModel($value);
                }
            }
        } catch (ValidateException|\Exception $e) {
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }

        //添加人才生命周期
//        $allRecord->addPersonAllocationModel ($param['clue_p_id'],message::$SUCC_PERSON_INSERT_MOBILE);
        $systemOperateLogModel->addOperate ($uid,message::$RERSON,message::$SUCC_PERSON_INSERT_MOBILE);
        return ReJson(message::$SUCC_CODE, message::$SUCC_INSERT_DATA);
    }


    /**
     *其他证书
     */
    //添加其他证书
    public function addPersonOtherCertificate(
        Request                    $request,
        CluePersonCertificate      $cer,
        Certificate                $certificateSer,
        RedisService $redisService,
        SystemOperateLog $systemOperateLogModel
    ){
        $param = $certificateSer->splitCer($request->post());
        $uid = $request->post ('user_login_id');

        if (empty($param['clue_p_id'])){
            return ReJson (message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);
        }

        try {
            Validate(Clue::class)->scene('otherCertificate')->check($param);

            $cer->addPersonCertificateModel($param);
        } catch (ValidateException|\Exception $e) {
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }

        //删除人才库缓存,重新加载
        $redisService->delPersonData ($param['clue_p_id']);
        //添加人才生命周期
//        $allRecord->addPersonAllocationModel ($param['clue_p_id'],message::$SUCC_PERSON_INSERT_CERTIFICATE);
        $systemOperateLogModel->addOperate ($uid,message::$RERSON,message::$SUCC_PERSON_INSERT_CERTIFICATE);
        return ReJson(message::$SUCC_CODE, message::$SUCC_INSERT_DATA);
    }

    //修改其他证书
    public function editPersonOtherCertificate(
        Request                    $request,
        CluePersonCertificate      $cer,
        Certificate                $certificateSer,
        RedisService $redisService,
        SystemOperateLog $systemOperateLogModel
    ){
        $param = $certificateSer->splitCer($request->post());
        $uid = $request->post ('user_login_id');

        try {
            if (empty($param['id'])) throw new \think\Exception(message::$ERR_PARAM_EMPTY, message::$ERROR_CODE);

            if (empty($param['clue_p_id'])) throw new \think\Exception(message::$ERR_PARAM_EMPTY, message::$ERROR_CODE);

            Validate(Clue::class)->scene('otherCertificate')->check($param);

            $cer->editCertificate($param);
            //删除人才库缓存,重新加载
            $redisService->delPersonData ($param['clue_p_id']);
        } catch (ValidateException|\Exception $e) {
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }

        //添加人才生命周期
//        $allRecord->addPersonAllocationModel ($param['clue_p_id'],message::$SUCC_PERSON_UPDATE_CERTIFICATE);
        $systemOperateLogModel->addOperate ($uid,message::$RERSON,message::$SUCC_PERSON_UPDATE_CERTIFICATE);

        return ReJson(message::$SUCC_CODE, message::$SUCC_UPDATE);
    }

    //删除其他证书
    public function delPersonOtherCertificate(
        Request                    $request,
        CluePersonCertificate      $cer,
        SystemOperateLog $systemOperateLogModel,
        RedisService $redisService
    ){
        $param = $request->post();
        $uid = $request->post ('user_login_id');

        if (!isset($param['id'])) throw new \think\Exception(message::$ERR_PARAM_EMPTY, message::$ERROR_CODE);

        if ($cer->delPersonCertificateModel($param)) {
            //添加人才生命周期
//            $allRecord->addPersonAllocationModel ($param['clue_p_id'],message::$SUCC_PERSON_DELETE_CERTIFICATE);
            $systemOperateLogModel->addOperate ($uid,message::$RERSON,message::$SUCC_PERSON_DELETE_CERTIFICATE);

            //删除人才库缓存,重新加载
            $redisService->delPersonData ($param['clue_p_id']);

            return ReJson(message::$SUCC_CODE, message::$SUCC_DATELE_DATA);
        }

        return ReJson(message::$ERROR_CODE, message::$ERR_DATELE_DATA);
    }

    /**
     *沟通记录
     */
    //添加沟通记录
    public function addPersonOtherCommunicate(
        Request                    $request,
        ClueCommunicateRecord      $cr,
        WorkPlan                   $workPlanModel,
        \app\model\UserMessage     $userMessageModel,
        CluePerson                 $personModel,
        \app\model\ClueEnterprise  $enterpriseModel,
        RedisService $redisService,
        SystemOperateLog $systemOperateLogModel
    ){

        $param = $request->post();
        $uid = $request->post ('user_login_id');
        if (empty($param['clue_p_id'])) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        //获取客户名称
        if ($param['type'] == 1) {
            $personData = $personModel->getIdPersonInfo($param['clue_p_id']);
            if ($personData) {
                $name = $personData['person_name'];
            } else {
                $name = '';
            }
        } else if ($param['type'] == 2) {
            $EnterData = $enterpriseModel->getIdInfo($param['clue_p_id']);
            if ($EnterData) {
                $name = $EnterData['enterprise_name'];
            } else {
                $name = '';
            }
        }
        $param['communicate_uid'] = $request->param('user_login_id');
        Db::startTrans();
        try {

            Validate(Clue::class)->scene('communicate')->check($param);

            $crData = $cr->addPersonCommunicateRecordModel($param);
            if ($param['next_communicate_date']) {
                //添加计划任务
                $wData = $workPlanModel->addPlanModel([
                    'custom_name' => $name,
                    'plan_date' => $param['next_communicate_date'],
                    'plan_content' => $param['next_plan_content'],
                    'create_uid' => $param['communicate_uid'],
                    'type' => 1,
                    'b_id' => $crData->id
                ]);

                //添加任务提醒
                $data = $userMessageModel->getWhereFindModel($param['next_communicate_date'],$param['user_login_id'],$wData->id);
                if ($data) {
                    $userMessageModel->esitIdFindModel($wData->id, ['execution_date' => $param['next_communicate_date']]);
                } else {
                    //添加信息提醒
                    $userMessageModel->addPlanModel($name, $param['user_login_id'],$uid, $wData->id, $param['next_communicate_date']);
                }

                //删除人才库缓存,重新加载
                $redisService->delPersonData ($param['clue_p_id']);

                //添加信息提醒
//                $userMessageModel->addPlanModel($name, $param['communicate_uid'], $uid,$crData->id, $param['next_communicate_date']);
            }
            db::commit();
        } catch (ValidateException|\Exception $e) {
            Db::backroll();
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }

        //添加人才生命周期
//        $allRecord->addPersonAllocationModel ($param['clue_p_id'],message::$SUCC_PERSON_INSERT_COMMUNICATE);
        $systemOperateLogModel->addOperate ($uid,message::$RERSON,message::$SUCC_PERSON_INSERT_COMMUNICATE);

        return ReJson(message::$SUCC_CODE, message::$SUCC_INSERT_DATA);
    }

    //修改沟通记录
    public function editPersonOtherCommunicate(
        Request                    $request,
        ClueCommunicateRecord      $cr,
        CluePersonAllocationRecord $allRecord,
        \app\model\UserMessage     $userMessageModel,
        WorkPlan                   $workPlanModel,
        CluePerson                 $personModel,
        \app\model\ClueEnterprise  $enterpriseModel,
        RedisService $redisService,
        SystemOperateLog $systemOperateLogModel
    ){
        $param = $request->post();
        $uid = $request->post('user_login_id');
        Db::startTrans();
        try {
            if (!isset($param['id'])) throw new \think\Exception(message::$ERR_PARAM_EMPTY, message::$ERROR_CODE);

            Validate(Clue::class)->scene('communicate')->check($param);

            $find = $cr->getIdFindModel($param['id']);

            $name = '';
            if ($find['type'] == 1) { //人才
                $personData = $personModel->getIdPersonInfo($find['clue_p_id']);
                if ($personData) {
                    $name = $personData['person_name'] ?: '';
                }
            } else if ($find['type'] == 2) { //企业
                $enData = $enterpriseModel->getIdInfo($find['clue_p_id']);
                if ($enData) {
                    $name = $enData['enterprise_name'] ?: '';
                }
            }

            //修改定时任务
            if ($find['next_communicate_date']) {
                //通过type=1 execution_date create_uid  b_id is_executed=2查询是否有对应沟通记录提醒 执行任务
                $data = $userMessageModel->getWhereFindModel($find['next_communicate_date'],$param['user_login_id'],$find['id']);

                if ($data) {
                    $userMessageModel->esitIdFindModel($data['id'], ['execution_date' => $param['next_communicate_date']]);
                } else {
                    //添加信息提醒
                    $userMessageModel->addPlanModel($name, $param['user_login_id'],$uid, $find['id'], $param['next_communicate_date']);
                }
            }

            if ($param['next_communicate_date']){
                //修改计划任务
                $workData = $workPlanModel->getWhereFindModel($find['next_communicate_date'], $param['user_login_id'], $find['id'], 2);

                if ($workData){
                    $workPlanModel->esitIdFindModel($workData['id'],['plan_date'=>$param['next_communicate_date'],'plan_content'=>$param['next_plan_content']]);
                    $wid = $workData['id'];
                }else{
                    //添加信息提醒
                    $wiData = $workPlanModel->addPlanModel([
                        'custom_name'=>$name,
                        'plan_date'=>$param['next_communicate_date'],
                        'plan_content'=>$param['next_plan_content'],
                        'create_uid' =>$uid,
                        'is_complete'=>2,
                        'type'=>1,
                        'b_id'=>$param['id']
                    ]);
                    $wid = $wiData->id;
                }
                //通过type=1 execution_date create_uid  b_id is_executed=2查询是否有对应沟通记录提醒 执行任务
                $data = $userMessageModel->getWhereFindModel($param['next_communicate_date'],$param['user_login_id'],$find['id']);

                if ($data) {
                    $userMessageModel->esitIdFindModel($data['id'], ['execution_date' => $param['next_communicate_date']]);
                } else {
                    //添加信息提醒
                    $userMessageModel->addPlanModel($name, $param['user_login_id'],$uid, $wid, $param['next_communicate_date']);
                }
            }

            $cr->editCommunicate($param);
            //删除人才库缓存,重新加载
            $redisService->delPersonData ($param['clue_p_id']);

            Db::commit();
        } catch (ValidateException|\Exception $e) {
            Db::rollback();
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }

        //添加人才生命周期
//        $allRecord->addPersonAllocationModel ($param['clue_p_id'],message::$SUCC_PERSON_UPDATE_COMMUNICATE);
        $systemOperateLogModel->addOperate ($uid,message::$RERSON,message::$SUCC_PERSON_UPDATE_COMMUNICATE);

        return ReJson(message::$SUCC_CODE, message::$SUCC_UPDATE);
    }

    //删除沟通记录
    public function delPersonOtherCommunicate(
        Request                    $request,
        ClueCommunicateRecord      $cr,
        CluePersonAllocationRecord $allRecord,
        \app\model\UserMessage     $userMessageModel,
        WorkPlan                   $workPlanModel,
        RedisService $redisService,
        SystemOperateLog $systemOperateLogModel
    ){
        $param = $request->post();
        $uid = $request->post ('user_login_id');

        try {
            if (!isset($param['id'])) throw new \think\Exception(message::$ERR_PARAM_EMPTY, message::$ERROR_CODE);

            $find = $cr->getIdFindModel($param['id']);

            //通过type=1 next_communicate_date uid  b_id is_executed=2查询是否有对应沟通记录提醒 执行任务
            $data = $userMessageModel->getWhereFindModel($find['next_communicate_date'],$param['user_login_id'],$find['id']);

            if ($data) {
                $userMessageModel->delWhereFindModel(1, $find['next_communicate_date'], $param['user_login_id'], $find['id'], 2);
            }
            //修改计划任务
            $workData = $workPlanModel->getWhereFindModel($find['next_communicate_date'], $param['user_login_id'], $find['id'], 2);
            if ($workData) {
                $workPlanModel->delIdFindModel($find['next_communicate_date'], $param['user_login_id'], $find['id'], 2);
            }

            $cr->delPersonCommunicateRecordModel($param['id']);
            //删除人才库缓存,重新加载
            $redisService->delPersonData ($param['clue_p_id']);
        } catch (ValidateException|\Exception $e) {
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }

        //添加人才生命周期
//        $allRecord->addPersonAllocationModel ($param['clue_p_id'],message::$SUCC_PERSON_DELETE_COMMUNICATE);
        $systemOperateLogModel->addOperate ($uid,message::$RERSON,message::$SUCC_PERSON_DELETE_COMMUNICATE);

        return ReJson(message::$SUCC_CODE, message::$SUCC_PERSON_DELETE_COMMUNICATE);
    }


    //获取电话状态
    public function getMobileStatus()
    {
        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, stateData::$_person_mobile_status);
    }

    //获取添加表单

    /**
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\DataNotFoundException
     */
    public function getPersonFrom(
        Request $request,
        Power   $power
    ){

        $aliasId = $request->get('aliasId');

        if (empty($aliasId)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        //获取模板字段权限id
//        databaseField::$rck_from['custom'] = $system->powerPoint($fieldList,array_values($fieldData),true);
        $fieldListTree = $power->getUserFieldPower($aliasId, $request->get('user_login_id'), true);

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $fieldListTree);
    }


    //身份证查重
    public function idCardCheckRepeat(Request $request, CluePerson $person)
    {
        $idCard = $request->post();

        try {
            Validate(Clue::class)->scene('idCard')->check($idCard);
        } catch (\Exception|ValidateException $e) {
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }

        $bool = $person->getPersonIdCard($idCard);

        if ($bool) {
            return ReJson(message::$ERROR_CODE, message::$ERR_PERSON_ID_CARD_ISSET);
        }
        return ReJson(message::$SUCC_CODE, message::$ERR_PERSON_ID_CARD_REPEAT);
    }


    //查询人才详情信息
    public function getPersonDetails(
        Request                       $request,
        CluePerson                    $person,
        ClueMobile                    $mobModel,
        ClueCommunicateRecord         $comRecord,
        CluePersonCertificate         $certifiModel,
        CluePersonAllocationRecord    $allocationRe,
        Certificate                   $certificate,
        OrderEnterpriseCompany        $company,
        OrderEnterpriseExchange       $exchange,
        OrderOtherCertificateBusiness $other,
        Power                         $power,
        CustomField $customField,
        CluePersonServer $cluePersonServer
    ){

        /**@param $人才id */
        $personId = $request->get('per_id');
        $uid = $request->get('user_login_id');

        //是否是查询下一条信息
        $next = $request->get('next') ?: 0;
        $isPower = $request->get('is_power') ?: 0;
        $param = $request->param ();


        //查询当前用户的ID数据集
        //参数验证
        $validate = new ClueUPersonList();
        if (!$validate->check($param)) {
            return ReJson(message::$ERROR_CODE, $validate->getError(), []);
        }
        //判断参数是否有值
        $flag = false;
        $key_arr = [
            'aliasId',
            'page',
            'pageNum',
            'user_login_id',
        ];
        foreach ($param as $key => $item) {
            if (in_array($key, $key_arr)) {
                continue;
            }
            if ($item) {
                $flag = true;
                break;
            }
        }
        //将每个参数整合为条件
        $person_ids = $cluePersonServer->spliceWhere($param);
        $person_ids = !$person_ids ? [0] : $person_ids;
        //用户person_ID
        $uid_person_ids = $person->getUidDataPersonId($uid);
        $person_ids = handlePersonIds($uid_person_ids, $person_ids, $flag);

        $dataId = $person->getOrderIdResultModel($person_ids);

        //查询数据库最大ID值
//        $maxId = $person->getMaxIdModel();
        //取下一条数据
        if (!empty($next)) {
            while (true) {
                $daPosition = array_search ($personId,$dataId);
                if (is_numeric ($daPosition)){
                    $daPosition++;
                    //如果要搜索下标值大于全部下标 则false
                    if($daPosition > count ($dataId)){
                        $personId  = '';
                        break;
                    }
                    $personId = $dataId[$daPosition];
                    break;
                }
////                if ($personId < $maxId){
//                if ($personId > 1) {
//                    $personId--;
//                    //查询是个人详情 还是管理详情
//                    if ($isPower == 1) {
//                        $nextData = Db::table('clue_person')
//                            ->where('id=' . $personId . ' and is_del=0 and f_uid=' . $uid)->order(['allocation_date'=>'DESC','create_date'=>'DESC'])->find();
//                    } elseif ($isPower == 2) {
//                        $userData = $power->getUserDataRange($uid);
//                        $idArr = implode($userData);
//                        $nextData = Db::table('clue_person')->where('id=' . $personId . ' and is_del=0')->whereIn('f_uid', $idArr)->find();
//                    }
//                    if (!empty($nextData)) {
//                        $personId = $nextData['id'];
//                        break;
//                    }
//                } else {
//                    break;
//                }
            }
        }


        if (empty($personId)) return ReJson(message::$ERROR_CODE, message::$SELECT_INFO_ERR);

        //查询基本信息
        $result['personInfo'] = Db::table('clue_person')->where('id=' . $personId . ' and is_del=0')->find();

        if ($result['personInfo']['is_wx'] == 0) {
            $result['personInfo']['is_wx'] = '';
        }

        //B证
        if ($result['personInfo']['certificate_b'] !== '') {
            $result['personInfo']['certificate_b'] = (int)$result['personInfo']['certificate_b'];
        }
        //社保
        if ($result['personInfo']['social_security'] !== '') {
            $result['personInfo']['social_security'] = (int)$result['personInfo']['social_security'];
        }
        //项目
        if ($result['personInfo']['project'] !== '') {
            $result['personInfo']['project'] = (int)$result['personInfo']['project'];
        }

        //时间字段如果为00：00:00 转空字符串
        foreach ($result['personInfo'] as &$item) {
            if ($item === "0000-00-00 00:00:00") {
                $item = '';
            }
        }

        //证书信息处理 4个字段合并certificate_id返给前段
        if (!empty($result['personInfo'])) {
            $originalData = CluePerson::find($personId);

            $result['personInfo']['certificate_id'] = [
                $originalData->getData('certificate_leixing'),
                $originalData->getData('certificate_leibie'),
                $originalData->getData('certificate_dengji'),
                $originalData->getData('certificate_zhuanye'),
            ];
        }

        //查询联系电话信息
        $result['mobileInfo'] = $mobModel->getPersonIdMobileModel($personId);

        //沟通记录
        $result['comReList'] = $comRecord->getPersonComRecordModel($personId);

        //其他证书
        $result['certificateList'] = $certifiModel->getPersonCertifiModel($personId);

        //最新一条沟通记录
        $result['comUpToDateRecord'] = $comRecord->getPersonIpToDateComRecordModel($personId);

        //生命周期
        $result['allReList'] = $allocationRe->getPersonCycleModel($personId);

        $result['custom'] = $customField->detailsCustomFieldHandle($result['personInfo']['custom']);

        //订单字段模板
        $zszcField = $power->getUserFieldPower('ddzszc', $request->param('user_login_id'));//证书注册
        $dzField = $power->getUserFieldPower('ddzszcdz', $request->param('user_login_id'));//倒证
        $zsblField = $power->getUserFieldPower('ddzsbl', $request->param('user_login_id'));//证书办理

        if ($result['personInfo']['person_id_card']){
            //查询人才关联订单
            $data = [];
            //先查询企业证书注册订单
            $comData = $company->getPersonIdCardListsModel($result['personInfo']['person_id_card']);
            //给所有证书注册添加字段

            foreach ($comData as $key => &$comDatum) {
                //ddzszc
                foreach ($comDatum as $k => $item) {

                    //如果是获取器数组 则只去text
                    if (is_array($item)) {
                        if (isset($item['text'])) {
                            $item = $item['text'] ?: '';
                        }
                    }

                    $data[$key]['id'] = $comDatum['id'];
                    $data[$key]['bh'] = $comDatum['certificate_code'];
                    $data[$key]['create_date'] = $comDatum['create_date'];
                    $data[$key]['leixing'] = '证书注册';
//                print_r ($k);
//                echo PHP_EOL;
                    if ($k == 'status') {
                        $data[$key]['status'] = $item;
                    }
                    foreach ($zszcField as $zszciItem) {
                        //如果模板字段等于订单详情字段 拼接字段name
                        if ($k == $zszciItem['alias_field_id']) {
                            if (!empty($zszciItem['name'])) {
                                $data[$key]['info'][] = ['id' => $zszciItem['name'], 'text' => $item];
                            }
                        }
                    }
                }
            }

            //查询倒证订单
            $exData = $exchange->getExchangeIdCardListModel($result['personInfo']['person_id_card']);

            $dzData = [];
            foreach ($exData as $keys => &$exDatum) {
                //ddzszcdz
//            $exDatum['leixing'] =  '倒证';
                foreach ($exDatum as $ks => $items) {
                    //如果是获取器数组 则只去text
                    if (is_array($items)) {
                        if (isset($items['text'])) {
                            $items = $items['text'] ?: '';
                        }
                    }
                    $dzData[$keys]['id'] = $exDatum['id'];
                    $dzData[$keys]['bh'] = $exDatum['certificate_code'];
                    $dzData[$keys]['create_date'] = $exDatum['create_date'];
                    $dzData[$keys]['leixing'] = '证书注册倒证';

                    if ($ks == 'status') {
                        $dzData[$keys]['status'] = $items;
                    }
                    foreach ($dzField as $dzItem) {
                        //如果模板字段等于订单详情字段 拼接字段name
                        if ($ks == $dzItem['alias_field_id']) {
                            if (!empty($dzItem['name'])) {
                                $dzData[$keys]['info'][] = ['id' => $dzItem['name'], 'text' => $items];
                            }
                        }
                    }
                }
            }

            //查询证书办理
            $otherData = $other->getIdCardDataModel($result['personInfo']['person_id_card']);

            $zsblData = [];
            foreach ($otherData as $keyss => &$otDatum) {
                //ddzsbl
//            $otDatum['leixing'] =  '证书办理';
                foreach ($otDatum as $kss => $itemss) {
                    //如果是获取器数组 则只去text
                    if (is_array($itemss)) {
                        if (isset($itemss['text'])) {
                            $itemss = $itemss['text'] ?: '';
                        }
                    }
                    $zsblData[$keyss]['id'] = $otDatum['id'];
                    $zsblData[$keyss]['bh'] = $otDatum['certificate_code'];
                    $zsblData[$keyss]['create_date'] = $otDatum['create_date'];
                    $zsblData[$keyss]['leixing'] = '证书办理';

                    if ($kss == 'status') {
                        $zsblData[$keyss]['status'] = $itemss;
                    }

                    foreach ($zsblField as $zsblItem) {
                        //如果模板字段等于订单详情字段 拼接字段name
                        if ($kss == $zsblItem['alias_field_id']) {

                            if (!empty($zsblItem['name'])) {
                                $zsblData[$keyss]['info'][] = ['id' => $zsblItem['name'], 'text' => $itemss];

                            }
                        }
                    }
                }

            }

            $result['orderInfo'] = array_merge($data, $dzData, $zsblData);
        }else{
            $result['orderInfo'] = [];
        }

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result);
    }

    //获取select值
    public function getSelectOption(Request $request, \app\service\Clue $clue, User $user, System $system)
    {
        $param = $request->get();

        if (!isset($param['option'], $param['option-data'])) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $result = $clue->getOption($param);

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result);
    }


    /********************************************************************************   回收站     *********************************************************/

    //人才回收站
    public function personRecycleList(
        Request           $request,
        CluePerson        $person,
        \app\service\Clue $clue,
        Power             $power,
        CluePersonServer  $cluePersonServer,
        CustomField                $customField
    ){
        $aliasId = $request->get('aliasId');
        $uid = $request->get('user_login_id');

        $page = $request->get('page') ?: 0;
        $pageNum = $request->get('pageNum') ?: stateData::$_page;
        $param = $request->get();
        //参数验证
        $validate = new ClueUPersonList();
        if (!$validate->check($param)) {
            return ReJson(message::$ERROR_CODE, $validate->getError(), []);
        }
        $flag = flagStatus($param);
        //将每个参数整合为条件
        $person_ids = $cluePersonServer->spliceWhere($param);
        $person_ids = !$person_ids ? [0] : $person_ids;

        $all_person_ids = $person->getDelEqRecycleIds();
        $ids = handlePersonIds($all_person_ids, $person_ids, $flag);
        $fieldListTree = $power->getUserFieldPower($aliasId, $uid);
        $result = $clue->personData($person->getDelEqRecycle($page, $pageNum, $ids), $uid);
        foreach($result as $key => $value){
            $result[$key] = $customField->listCustomFieldHandle($value);
        }
        return ReJson(
            message::$SUCC_CODE,
            message::$SUCC_SELECT_DATA,
            [
                'data' => $result,
                'power' => $fieldListTree
            ],
            [
                'pageNumber' => $pageNum,
                'total' => $person->getDelEqRecycleCount($ids),
            ]
        );
    }

    //企业电销(1) 网销(2) 回收站
    public function enterpirseRecycleList(
        Request                     $request,
        \app\model\ClueEnterprise   $enterprise,
        Certificate                 $certificate,
        Power                       $power,
        \app\service\ClueEnterprise $clueEnterprise,
        \app\service\Clue           $clueSer,
        \app\service\Order          $orderSer,
        CustomField                $customField,
        RedisService $redisService
    ){
        $aliasId = $request->get('aliasId');
        $type = $request->get('type');
        $page = $request->get('page') ?: 0;
        $pageNum = $request->get('pageNum') ?: stateData::$_page;
        $uid = $request->get('user_login_id');
        $param = $request->get();

        $validate = new ClueEnterpriseValidate();
        if (!$validate->check($param)) {
            return ReJson(message::$ERROR_CODE, $validate->getError(), []);
        }
        $flag = flagStatus($param);
        $ids = $clueEnterprise->spliceWhere($param);
        $ids = !$ids ? [0] : $ids;
        $all_ids = $enterprise->getDelEqRecycleIds($type);
        $ids = handlePersonIds($all_ids, $ids, $flag);
        $fieldListTree = $power->getUserFieldPower($aliasId, $uid);

        $resultId = $enterprise->getDelEqRecycle($type, $page, $pageNum, $ids);
        //获取redis数据
        $result = $redisService->getEnterData ($resultId,$uid);

        return ReJson(
            message::$SUCC_CODE,
            message::$SUCC_SELECT_DATA,
            [
                'data' => $result,
                'power' => $fieldListTree
            ],
            [
                'pageNumber' => $pageNum,
                'total' => $enterprise->getDelEqRecycleCount($type, $ids),
            ]
        );
    }

    //重点客户设置
    public function setZD(
        Request      $request,
        CluePerson   $person,
        RedisService $redisService,
        SystemOperateLog $systemOperateLogModel
    ){
        $id = $request->post('id');
        $uid = $request->post ('user_login_id');

        if (empty($id)) return ReJson(message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        //先查询是否是重点客户
        $personData = $person->getIdPersonInfoModel($id);

        if (empty($personData)) {
            return ReJson(message::$ERROR_CODE, message::$ERR_PERSON_ID_CARD_REPEAT);
        }

        if ($personData['is_zd'] == 1) {
            $op = $person->setZDModel($id);
        } else {
            $op = $person->cancellationZDModel($id);
        }
        //更新缓存
        $redisService->updatePersonData ($person->getIdPersonInfoModel($id),$uid);
        //添加系统日志
        $systemOperateLogModel->addOperate ($uid,message::$RERSON,message::$SUCC_PERSON_SYSTEM_ZDKH);

        if ($op) {
            return ReJson(message::$SUCC_CODE, message::$SUCC_OPERATE);
        } else {
            return ReJson(message::$ERROR_CODE, message::$ERR_OP);
        }
    }
}